<?php declare(strict_types=1);

namespace App\Listener;

use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Event\ValidatorFactoryResolved;
use Hyperf\Validation\Validator;

#[Listener]
class ValidatorFactoryResolvedListener implements ListenerInterface
{

        public function listen(): array
        {
                return [
                        ValidatorFactoryResolved::class,
                ];
        }

        public function process(object $event): void
        {
                /**  @var ValidatorFactoryInterface $validatorFactory */
                $validatorFactory = $event->validatorFactory;
                // 注册了 foo 验证器
                $validatorFactory->extend('mobile_number', function (string $attribute, mixed $value, array $parameters, Validator $validator): bool {
                        if (!preg_match('/^1[3456789]{1}\d{9}$/', $value)) {
                                return false;
                        }
                        return true;
                });
                // 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符这里扩展了 :foo 占位符
                $validatorFactory->replacer('mobile_number', function (string $message, string $attribute, string $rule, array $parameters) {
                        return str_replace(':mobile_number', $attribute, $message);
                });
        }
}
